/**
 * Created by TomSean on 2017/3/20.
 */
var CouponManager = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
CouponManager.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : "search_btn", fs : this.findData},
            {fName : "reset_btn", fs : this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#preferentialPhysicalType'), parentModelKey:BASIS.PREFERENTIAL_TICKET_TYPE.ROOT}, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#ticketSituation'), parentModelKey:BASIS.PREFERENTIAL_TICKET_SITUATION.ROOT}, this);
        this.createList();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    deleteData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = "";
        _this.$parent.find('input[name=id]:checked').each(function(inx, itm) {
            ids += $(itm).val() + ",";
        });
        if (ids == "") {
            notification({title : "操作失败", message : "请至少选择一条数据来删除"}, 'info');
            return;
        }
        ids = ids.substring(0, ids.length-1);
        notification({title:"确认信息", message:"确定需要删除选中的信息？"}, 'confirm', {
            callback : function() {
                JsonpAjax(baseApiPath + "coupon/delete?ids="+ids, undefined, "json", function(res) {
                    _this.findData();
                });
            }
        });
    },
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }

        var params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        var dataT = {jsonParam : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({
            url : baseApiPath + "coupon/list",
            data : dataT,
            dataType : "odata"
        });
        var grid = _this.$parent.find('#coupon_data_list').data('kendoGrid');
        grid.setDataSource(dataSource);
    },
    createList : function() {
        var _this = this;
        var columns = [
            {
                width:30,
                headerTemplate : '<input type="checkbox" gridId="coupon_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="id" value="${id}" />'
            },
            {
                title: "优惠劵码",
                field: "preferentiaIdent"
            },
            {
                title : "卡劵类型",
                template:'#:Utils.getModelNameByParentKey(BASIS.PREFERENTIAL_TICKET_TYPE.ROOT, crPreferentialType)#'
            },
            {
                title : "录属项目 (优惠项目编号)",
                template : '${crPreferentialInfo.preferentialName} <small>(${crPreferentialInfo.preferentialCode})</small>'
            },
            {
                title : "使用情况",
                template:'#:Utils.getModelNameByParentKey(BASIS.PREFERENTIAL_TICKET_SITUATION.ROOT, employType)#'
            },
            {
                title : "使用时间",
                template : "${null == data.employTime?'暂未使用':data.employTime}"
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#coupon_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find("input[type=checkbox]").val();
                });
                _this.selectRowId = selected[0];
            }
        });
    },
    openNewWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
            title : "新增优惠劵",
            height : "620px",
            width : "730px",
            resizable : false,
            content : "views/parkLotCenter/discountManage/coupon_edit.html"
        });
    }
}

var CouponEdit = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
CouponEdit.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : "autocreate_btn", fs : this.autoCreate},
            {fName : "save_btn", fs : this.saveInfo},
            {fName : "cancel", fs : function() { $('#' + couponManager.editWindow).data('kendoWindow').close() }},
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#preferentialPhysicalType'), parentModelKey : BASIS.PREFERENTIAL_TICKET_TYPE.ROOT}, this);
        $("#autoCreateNumber").kendoNumericTextBox({
            format:"d",
            min: 1,
            max: 9999,
            step: 1
        });
        var _this = this;
        JsonpAjax(baseApiPath + "preferential/valid", undefined, "json", function(res) {
            var list = res;
            var data = [];
            if (list.length < 1) {
                data.push({text:"--暂无可选活动--", value:"0"});
            } else {
                for (var i = 0; i < list.length; i++) {
                    data.push({text:list[i].preferentialName, value:list[i].preferentialCode});
                }
            }
            _this.$parent.find('#preferentialCode').kendoDropDownList({
                dataTextField: "text",
                dataValueField: "value",
                dataSource: data,
                index:0,
                select : function(e) {
                    var dataItem = this.dataItem(e.item);
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].preferentialCode == dataItem.value) {
                            _this.$parent.find('#beginTime').val(list[i].beginTime);
                            _this.$parent.find('#endTime').val(list[i].endTime);
                            break;
                        }
                    }
                }
            });
        });
    },
    autoCreate : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (validityForm(_this.$parent)) {
            var num = _this.$parent.find('#autoCreateNumber').val();
            var t = _this.$parent.find('#preferentialPhysicalType').val();
            if (isEmpty(t)) {
                notification({title : "操作失败", message : "请选择优惠券类型"}, 'info');
                return;
            }
            _this.$parent.find('.autocreate_button').css({"background":"#2f8feb","color":"#fff"});
            _this.$parent.find('.autocreate_button').html('正在生成，请稍后... 0%');
            var dataT = {num : num, preferentialCode : ""};
            JsonpAjax(baseApiPath + "coupon/getTicketCode", dataT, "json", function(res) {
                _this.$parent.find('.autocreate_button').html('正在生成，请稍后... 70%');
                var $table = _this.$parent.find('#ticket_data_list');
                $table.find('.preferential_ticket').remove();
                var list = res;
                _this.tickets = list;
                for (var i = 1; i <= list.length; i++) {
                    var ticket = document.createElement("div");
                    ticket.className = "preferential_ticket";

                    var header = document.createElement("div");
                    header.className = "ticket_header";

                    var title = document.createElement("p");
                    title.innerHTML = "优惠劵";
                    title.className = "ticket_title";


                    var no = document.createElement("div");
                    no.innerHTML = "<small>序号</small>"+i;
                    no.className = "ticket_no";

                    var code = document.createElement("div");
                    code.className = "ticket_code";
                    var span = document.createElement("span");
                    span.innerHTML = list[i-1];
                    code.appendChild(span);

                    var pic = document.createElement("div");

                    if (t == 0) {
                        var qrcode = new QRCode(pic, {
                            width : 180,//设置宽高
                            height : 180
                        });
                        qrcode.makeCode(list[i-1]);
                    } else if (t == 1) {
                        var img = document.createElement("img");
                        JsBarcode(img, list[i-1],  {displayValue:false});
                        img.style.width = "270px";
                        pic.appendChild(img);
                    }
                    var content = document.createElement("div");
                    content.className = "ticket_content";
                    header.appendChild(no);
                    header.appendChild(title)
                    content.appendChild(code);
                    content.appendChild(pic);
                    ticket.appendChild(header);
                    ticket.appendChild(content);
                    $table[0].appendChild(ticket);
                    ticket.style.display = "inline-block";
                }
                _this.$parent.find('.autocreate_button').html('生成完毕 100% (点我可以重新生成)');
                _this.$parent.find('.autocreate_button').css({"background":"transparent","color":"#ff0000"});
            });
        }
    },
    saveInfo : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var val = _this.$parent.find('#preferentialCode').val();
        var t = _this.$parent.find('#preferentialPhysicalType').val();
        if (isEmpty(val)) {
            notification({title : "操作失败", message : "请先选择活动项目"}, 'info');
            return;
        }
        if (_this.tickets == undefined || isEmpty(_this.tickets)) {
            notification({title : "操作失败", message : "请先生成优惠券！"}, 'info');
            return;
        }
        var dataT = {code : val, type : t, tickets : JSON.stringify(_this.tickets)};
        JsonpAjax(baseApiPath + "coupon/save", dataT, "json", function(res) {
            couponManager.findData();
            $('#' + couponManager.editWindow).data('kendoWindow').close();
        });
    }
}